#include "AliOSSRemoveRequest.h"

#include <QObject>
#include <AliOSSAdapter.h>
#include <QNetworkAccessManager>
namespace AliOSS
{
	AliOSSRemoveRequest::AliOSSRemoveRequest(
		QObject *parent,
		QNetworkAccessManager *networkAccessManager,
		const QString &bucket,
		const QString &accessId) 
		:
        QObject(parent) ,
        networkAccessManager(networkAccessManager),
		bucket(bucket),
        accessId(accessId)
	{

	}

	AliOSSRemoveRequest::~AliOSSRemoveRequest()
	{

	}

	void AliOSSRemoveRequest::doRemove()
	{
		QString authorization = "OSS [accessKeyId]:[signature]";
		authorization.replace("[accessKeyId]", accessId);
		authorization.replace("[signature]", signature);

		QString url = "http://[bucket].oss-cn-shenzhen.aliyuncs.com/[object]";
		url.replace("[bucket]", bucket);
		url.replace("[object]", path);

		QNetworkRequest request(url);
		request.setRawHeader("Date", dtstr.toLocal8Bit());
		request.setRawHeader("Authorization", authorization.toLocal8Bit());

		reply = networkAccessManager->deleteResource(request);
		reply->setParent(this); // set auto-delete action with uploader
		QObject::connect(reply, &QNetworkReply::finished, this, &AliOSSRemoveRequest::onRequestFinished);
		QObject::connect(reply, &QNetworkReply::uploadProgress, this, &AliOSSRemoveRequest::uploadProgress);
		QObject::connect(reply, static_cast<void(QNetworkReply::*)(QNetworkReply::NetworkError)>(&QNetworkReply::error), this, &AliOSSRemoveRequest::uploadError);

		// debug info
		QObject::connect(reply,
			static_cast<void(QNetworkReply::*)(QNetworkReply::NetworkError)>(&QNetworkReply::error),
			[this]()
		{
			qWarning().noquote() << QString("Upload Error (%1:%2) : \n%3")
				.arg(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt())
				.arg(reply->attribute(QNetworkRequest::HttpReasonPhraseAttribute).toString())
				.arg(QString::fromUtf8(reply->readAll()));
		});
	}

	void AliOSSRemoveRequest::setNeededInformation(const QString &datetimestr, const QString &signature)
	{
		this->signature = signature;
		this->dtstr = datetimestr;
	}

	void AliOSSRemoveRequest::onRequestFinished()
	{
		if (isOk())
			uploadFinished();
		else
			uploadFailed();
	}

	bool AliOSSRemoveRequest::isOk()
	{
        int code = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
		if (code != 200 && code != 204)
		{
			qWarning().noquote() << QString("Remove finished but failed (%1:%2) : \n%3")
				.arg(code)
				.arg(reply->attribute(QNetworkRequest::HttpReasonPhraseAttribute).toString())
				.arg(QString::fromUtf8(reply->readAll()));
            return false;
		}
        return true;
	}

	void AliOSSRemoveRequest::prepare(const QString & path)
	{
		this->path = path;
	}

}
